<template>
  <div class="terminal-wrap">
    <div ref="terminalRef"></div>
  </div>
</template>
<script setup lang="ts">
import { Terminal } from 'xterm'
import { FitAddon } from 'xterm-addon-fit'
import 'xterm/css/xterm.css'
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const terminalRef = ref<HTMLElement>()

/**
 * 执行操作
 */
const start = () => {
  const protocol = location.protocol === 'https:' ? 'wss' : 'ws'
  const url = `${protocol}://${location.host}/base_platform/ws/${route.query.route}/${route.query.id}/?${route.query.remote_ip}`
  const socket = new WebSocket(url)
  const cols = Math.floor(window.innerWidth / 9)
  const rows = Math.floor(window.innerHeight / 15)
  const terminal = new Terminal({
    rows,
    cols,
    fontSize: 15,
    scrollback: 500,
    convertEol: true,
    cursorBlink: true,
    disableStdin: false,
    cursorStyle: 'block',
    theme: {
      foreground: '#00ff00', //字体
      background: 'black', //背景色#060101
      cursor: '#00ff00' //设置光标
    }
  })
  terminal.open(terminalRef.value as HTMLElement)
  terminal.loadAddon(new FitAddon())
  socket.onopen = () => {
    terminal.focus()
    socket.send('terminal monitor')
    socket.send('\r')
  }
  terminal.onData((val: string) => {
    socket.send(val)
  })
  socket.onmessage = (evt: MessageEvent<any>) => {
    terminal.write(evt.data.toString())
  }
  socket.onclose = () => {}
  socket.onerror = () => {}
}

onMounted(() => {
  start()
})
</script>
<style lang="scss" scoped>
.terminal-wrap {
  overflow: hidden;
  height: 100vh;
}
</style>
